import { ChatOpenAI, OpenAIEmbeddings } from '@langchain/openai';
import { log } from './logger';

// DeepSeek模型配置选项
interface DeepSeekConfig {
  temperature?: number;
  maxTokens?: number;
  topP?: number;
  frequencyPenalty?: number;
  presencePenalty?: number;
  model?: string;
}

// 默认配置
const DEFAULT_CONFIG: DeepSeekConfig = {
  temperature: 0.7,
  maxTokens: 2000,
  topP: 0.9,
  frequencyPenalty: 0.1,
  presencePenalty: 0.1,
  model: 'deepseek-chat',
};

// 不同场景的预设配置
export const DEEPSEEK_PRESETS = {
  // 创意写作模式
  creative: {
    temperature: 0.9,
    maxTokens: 3000,
    topP: 0.95,
    frequencyPenalty: 0.2,
    presencePenalty: 0.2,
  },
  // 分析模式
  analytical: {
    temperature: 0.3,
    maxTokens: 2500,
    topP: 0.8,
    frequencyPenalty: 0.0,
    presencePenalty: 0.0,
  },
  // 对话模式
  conversational: {
    temperature: 0.7,
    maxTokens: 2000,
    topP: 0.9,
    frequencyPenalty: 0.1,
    presencePenalty: 0.1,
  },
  // 简洁模式
  concise: {
    temperature: 0.5,
    maxTokens: 1000,
    topP: 0.85,
    frequencyPenalty: 0.15,
    presencePenalty: 0.1,
  },
  // RAG模式
  rag: {
    temperature: 0.4,
    maxTokens: 2500,
    topP: 0.8,
    frequencyPenalty: 0.0,
    presencePenalty: 0.05,
  },
};

// 创建DeepSeek客户端实例
function createDeepSeekClient(
  config: DeepSeekConfig = DEFAULT_CONFIG
): ChatOpenAI {
  return new ChatOpenAI({
    modelName: config.model || 'deepseek-chat',
    openAIApiKey: process.env.DEEPSEEK_API_KEY,
    configuration: {
      baseURL: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/v1',
    },
    temperature: config.temperature,
    maxTokens: config.maxTokens,
    topP: config.topP,
    frequencyPenalty: config.frequencyPenalty,
    presencePenalty: config.presencePenalty,
  });
}

// 默认DeepSeek聊天模型
export const deepseekChat = createDeepSeekClient();

// 获取优化的DeepSeek客户端
export function getOptimizedDeepSeekClient(
  preset: keyof typeof DEEPSEEK_PRESETS | DeepSeekConfig
): ChatOpenAI {
  if (typeof preset === 'string') {
    return createDeepSeekClient(DEEPSEEK_PRESETS[preset]);
  }
  return createDeepSeekClient(preset);
}

// DeepSeek嵌入模型配置（使用DeepSeek API）
export const embeddingModel = new OpenAIEmbeddings({
  modelName: process.env.EMBEDDING_MODEL || 'text-embedding-3-small',
  openAIApiKey: process.env.DEEPSEEK_API_KEY,
  configuration: {
    baseURL: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/v1',
  },
  dimensions: parseInt(process.env.EMBEDDING_DIMENSIONS || '1536'),
});

// 备用OpenAI嵌入模型（如果需要）
export const openaiEmbeddingModel = new OpenAIEmbeddings({
  modelName: 'text-embedding-3-small',
  openAIApiKey: process.env.OPENAI_API_KEY,
  configuration: {
    baseURL: 'https://api.openai.com/v1',
  },
  dimensions: 1536,
});

// 文本分块配置
export const chunkConfig = {
  chunkSize: parseInt(process.env.CHUNK_SIZE || '1000'),
  chunkOverlap: parseInt(process.env.CHUNK_OVERLAP || '200'),
};

// 测试DeepSeek连接
export async function testDeepSeekConnection() {
  try {
    const response = await deepseekChat.invoke(
      'Hello, this is a test message.'
    );
    log.info('DeepSeek API连接成功');
    return true;
  } catch (error) {
    log.error('DeepSeek API连接失败', error);
    return false;
  }
}

// 测试嵌入模型连接
export async function testEmbeddingConnection() {
  try {
    const embeddings = await embeddingModel.embedQuery('This is a test query.');
    log.info('嵌入模型连接成功');
    return true;
  } catch (error) {
    log.error('嵌入模型连接失败', error);
    return false;
  }
}
